package com.zq.download.utils;

import android.text.TextUtils;

import java.net.URLConnection;

/**
 * Created by zhangqiang on 17-6-23.
 */

public class DownloadUtils {

    private static String getFileNameFromResponse(URLConnection response){

        final String FILE_NAME_PREFIX = "filename=";

        String content_disposition = response.getHeaderField("content-disposition");
        if(TextUtils.isEmpty(content_disposition)){
            return null;
        }
        String[] items = content_disposition.split(";");

        for (String item:
                items) {

            item = item.trim();
            if(item.startsWith(FILE_NAME_PREFIX)){

                return item.substring(FILE_NAME_PREFIX.length());
            }
        }
        return null;
    }


    private static String getFileNameFromURL(String url){

        return url.substring(url.lastIndexOf("/") + 1);
    }

    public static String getFileName(URLConnection response, String url){

        String fileName = getFileNameFromResponse(response);
        if(TextUtils.isEmpty(fileName)){

            fileName = getFileNameFromURL(url);
        }
        return fileName;
    }

    private static String getTaskTag(String url,String filePath){

        return MD5Utils.getStringMD5(url + filePath);
    }
}
